package org.simplextensions.configuration;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class ConfigurationReader {

	private final static String EXTENSIONS_XML = "extensions.xml";

	private static final Log log = LogFactory.getLog(ConfigurationReader.class);

	// private final static String LISTENERS_OBJECT_FACTORY_PACKAGE =
	// "org.simplextensions.listeners";

	private static Enumeration<URL> getUrlList() throws IOException {
		return Thread.currentThread().getContextClassLoader().getResources(EXTENSIONS_XML);
	}

	public static List<BundleConfiguration> getBundleList() throws IOException {
		List<BundleConfiguration> bundleList = new ArrayList<BundleConfiguration>();
		log.info("-------------------- finding bundles ---------------");
		for (Enumeration<URL> urlList = getUrlList(); urlList.hasMoreElements();) {
			try {
				URL url = urlList.nextElement();
				log.info(url);
				bundleList.add(read(url));
			} catch (JAXBException e) {
				e.printStackTrace();
			}
		}
		log.info("-------------------- end of finding bundles ---------------");
		return bundleList;
	}

	public static BundleConfiguration read(URL url) throws JAXBException {
		JAXBContext jc = JAXBContext.newInstance(ExtensionsConfiguration.class.getPackage().getName());
		Unmarshaller u = jc.createUnmarshaller();
		return new BundleConfiguration(((JAXBElement<ExtensionsConfiguration>) u.unmarshal(url)).getValue(), url);
	}
}
